'use client'

import { useState, useEffect } from 'react'
import { Product } from '@/types'
import { ProductForm } from '@/components/products/product-form'
import { Metadata } from "next"

export const metadata: Metadata = {
  title: "商品管理 - 商场销售系统",
  description: "商品管理页面",
}

export default function ProductsPage() {
  const [products, setProducts] = useState<Product[]>([])
  const [categories, setCategories] = useState<{ id: number; name: string }[]>([])
  const [editingProduct, setEditingProduct] = useState<Product | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // 获取商品列表和分类列表
    Promise.all([
      fetch('/api/products').then(res => res.json()),
      fetch('/api/categories').then(res => res.json())
    ]).then(([productsData, categoriesData]) => {
      console.log('Categories loaded:', categoriesData) // 调试用
      setProducts(productsData)
      setCategories(categoriesData)
      setLoading(false)
    }).catch(error => {
      console.error('Failed to fetch data:', error)
      setLoading(false)
    })
  }, [])

  if (loading) {
    return <div>加载中...</div>
  }

  const handleEdit = (product: Product) => {
    setEditingProduct(product)
  }

  const handleDelete = async (id: number) => {
    const response = await fetch(`/api/products/${id}`, { method: 'DELETE' })
    if (response.ok) {
      setProducts(products.filter(product => product.id !== id))
    }
  }

  return (
    <div className="space-y-4 p-8">
      <h1 className="text-2xl font-bold">商品管理</h1>
      <ProductForm 
        product={editingProduct}
        categories={categories}
        onClose={() => setEditingProduct(null)}
        onSave={(updatedProducts) => setProducts(updatedProducts)}
      />
      <table className="min-w-full border-collapse border border-gray-300">
        <thead>
          <tr>
            <th className="border border-gray-300 p-2">商品名称</th>
            <th className="border border-gray-300 p-2">商品编码</th>
            <th className="border border-gray-300 p-2">分类</th>
            <th className="border border-gray-300 p-2">单位</th>
            <th className="border border-gray-300 p-2">价格</th>
            <th className="border border-gray-300 p-2">库存</th>
            <th className="border border-gray-300 p-2">操作</th>
          </tr>
        </thead>
        <tbody>
          {products.map(product => (
            <tr key={product.id}>
              <td className="border border-gray-300 p-2">{product.name}</td>
              <td className="border border-gray-300 p-2">{product.code}</td>
              <td className="border border-gray-300 p-2">{product.category?.name}</td>
              <td className="border border-gray-300 p-2">{product.unit}</td>
              <td className="border border-gray-300 p-2">¥{product.price.toString()}</td>
              <td className="border border-gray-300 p-2">{product.stock}</td>
              <td className="border border-gray-300 p-2">
                <button onClick={() => handleEdit(product)} className="text-blue-600 hover:underline">编辑</button>
                <button onClick={() => handleDelete(product.id)} className="text-red-600 hover:underline ml-2">删除</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
} 